<template>
  <el-dialog v-model="visible" :title="title" :before-close="onVisable" :draggable="true" :width="800">
    <el-form ref="formRef" :model="dataForm" :rules="ruleList" label-width="160px">
      <div class="flex-sc warp ww100">
        <!-- 主键 -->
        <el-form-item label="主键" class="ww100" v-if="props.state.editKey&&title=='修改'">
          <el-input size="large" v-model="dataForm[props.state.key]" placeholder="请输入" :disabled="true"/>
        </el-form-item>
        <div v-for="(item, index) in editFromInfo" :key="index" :style="{width: props.state.editCol? (100/props.state.editCol) + '%' : 100 + '%' }" >
          <div v-if="!item.condit || dataForm[item.condit[0]]==item.condit[1]">
            <el-form-item :label="item.name" :prop="item.key" v-if="title == '新增' || item.editshow">
              <span @click="handleSync('comm_params')" class="i1 cursor" v-if="dataForm[state.key] && item.key == 'comm_params'">同步通讯参数</span>
              <!-- 输入框 -->
              <el-input size="large" v-model="dataForm[item.key]" placeholder="请输入" v-if="item.type[0]=='input'"  :type="item.type[1]?item.type[1]:'text'"  :maxlength="item.maxlength?item.maxlength:''" :disabled="item.editshow=='disabledAll'?true:title=='修改'&&item.editshow=='disabled'?true:false"/>
              <!-- 密码框 -->
              <el-input size="large" v-model="dataForm[item.key]" placeholder="请输入" v-if="item.type[0]=='password'" :maxlength="item.maxlength?item.maxlength:''" :disabled="item.editshow=='disabledAll'?true:title=='修改'&&item.editshow=='disabled'?true:false" type="password" show-password />
              <!-- 文本框 -->
              <el-input size="large" v-model="dataForm[item.key]" placeholder="请输入" v-if="item.type[0]=='textarea'" :maxlength="item.maxlength?item.maxlength:''" :disabled="item.editshow=='disabledAll'?true:title=='修改'&&item.editshow=='disabled'?true:false"
              type="textarea" :autosize="{ minRows: item.type[1]?item.type[1][0]:3, maxRows: item.type[1]?item.type[1][1]:5 }" />
              <!-- 下拉框 -->
              <el-select size="large" v-model="dataForm[item.key]" placeholder="请选择" v-if="item.type[0]=='select'" style="width:100%" clearable :disabled="item.editshow=='disabledAll'?true:title=='修改'&&item.editshow=='disabled'?true:false" @change="changeFiled(item, dataForm[item.key])">
                <el-option v-for="sel in item.type[1]" :key="sel[item.type[2]]" :label="sel[item.type[3]]" :value="sel[item.type[2]]" />
              </el-select>
              <!-- 时间 -->
              <el-date-picker size="large" v-model="dataForm[item.key]" placeholder="请选择" v-if="item.type[0]=='time'" style="width: 100%;"  type="datetime" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" :disabled="item.editshow=='disabledAll'?true:title=='修改'&&item.editshow=='disabled'?true:false"/>
              <!-- 树结构 -->
              <el-tree-select size="large" v-model="dataForm[item.key]" placeholder="请选择" v-if="item.type[0]=='tree'" @change="changeSelect(item, dataForm[item.key])"
              ref="treeRef" class="ww100 c8" :default-expand-all="true" highlight-current accordion clearable filterable check-strictly :render-after-expand="false"
              :data="tree" :props="defaultProps" :node-key="item.type[2]?item.type[2]:treeId" :disabled="item.editshow=='disabledAll'?true:title=='修改'&&item.editshow=='disabled'?true:false"/>
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" type="info" class="i23 bg-white" @click="onVisable">取 消</el-button>
        <el-button size="large" type="info" class="white bgi22" @click.stop="handleSubmit(formRef)">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import api from '../api'
  import CryptoJS from 'crypto-js'
  const { proxy }:any = getCurrentInstance()
  const publicStore = proxy.publicStore()
  let editFromInfo = $ref([])
  let visible = $ref(false)
  let title = $ref('')
  let dataForm = $ref({})
  let formRef = ref()
  let ruleList= $ref({})
  let treeRef = $ref(null)
  let treeId = $ref('id')
  let tree = $ref([])
  const defaultProps = {
    children: 'children',
    label: 'name',
  }   
  const props = defineProps({
    state: {
      type: [Object, Array],
      default: ()=>{return {}}
    },
  })
  const emit = defineEmits(['init', 'changeSelect'])

  // 打开关闭弹窗
  const onVisable = async (val, type) => {
    visible = !visible
    if (!visible) return
    // 多个
    editFromInfo = type?props.state['editFrom'+type]:props.state.editFrom
    // 标题
    title = val && val.hasOwnProperty(props.state.key)? '修改':'新增'
    // 表单
    if(title == '修改' && !proxy.isNull(props.state.editField)){
      Object.keys(props.state.editField).forEach(key=>{props.state.editField[key]=val[key]})
    }
    dataForm = {}
    dataForm = Object.assign({}, !proxy.isNull(props.state.editField)&&title == '修改'? props.state.editField : val)
    // 规则
    ruleList = {}
    // 获取属性
    editAttr(props.state.editFrom)
  }
  // 获取属性
  const editAttr = async(editFrom) => { 
    if(!editFrom) return false
    editFrom.forEach(item => {
      if(Array.isArray(item)){
         return editAttr(item)
      }else{
        // 获取规则
        if(item.required){
          if(title == '新增' || item.editshow){
            let rule = proxy.varObj(item.key, [
              {
                required: true, 
                message: item.type[0]=='input'||item.type[0]=='textarea'?'请输入':'请选择', 
                trigger: item.type[0]=='input'||item.type[0]=='textarea'?['blur']:['blur','change'], 
                pattern: item.pattern?item.pattern:''
              }])
            Object.assign(ruleList, rule)
          }
        }
        // 时间转化
        if(item.type[0]=='time'){
          dataForm[item.key] = title=='修改'? proxy.parseTime(dataForm[item.key]) : proxy.parseTime(new Date())
        }
        // 获取树结构
        if(item.type[0]=='tree'){
          if(item.type.length<4) return false
          tree = proxy.treeData(item.type[1], item.type[2], item.type[3], 'children')
          if (item.type[4]) {
            let json = proxy.varObj(item.type[2], '0')
            let json2 = proxy.varObj(item.key, '0')
            json.name = item.type[4]
            Object.assign(json, json2)
            tree.unshift(json)
          }
        }
      }
    })
  }

  const changeFiled = async(val, value) => {
    if(!val.relation) return
    value = val.type[1].find(a=>{ return a[val.key] == value})[val.relation[0]]
    dataForm[val.relation[0]] = value
  }
  
  const changeSelect = async(val, value) => {
    if(!val.relation) return
    emit('changeSelect', value)
  }

  // 提交
  const handleSubmit = (formEl) => {
    formEl.validate(valid => {
      if (valid) {
        let editFrom = Object.assign({}, dataForm)
        let tempFrom = ''
        tempFrom = props.state.editFrom.find(a=>{return a.type[0] == 'time'})
        if(tempFrom){
          editFrom[tempFrom.key] = new Date(editFrom[tempFrom.key]).getTime()
        }
        tempFrom = props.state.editFrom.find(a=>{return a.type[0] == 'password'})
        if(tempFrom && tempFrom.key == 'password' && editFrom[tempFrom.key]){
          editFrom[tempFrom.key] = CryptoJS.MD5(editFrom[tempFrom.key].toString().trim()).toString().toUpperCase();
        }
        upd(editFrom, props.state.query, props.state.key, title)
      }
    })
  }

  const upd = (from:any, query:any, key:any, mark:any) => {
    delete from.children
    from.o = query.length?query[0].o : query.o
    from.a = mark == '修改'? "修改" : '新增'
    from.t = mark == '修改'? "upd" : "add"
    if(key){
      from[key] = from[key]? from[key] : new Date().getTime()
    }
    if(from.o == "o_sensor_template") {
      delete from.id 
      delete from.nodetype
      from = proxy.renameProperty(from, 'upid', 'class')
    }
    let allFrom = [from]
    api.updateApi(allFrom).then((res:any) => {
      if(res.errcode == 0){
        ElNotification({ title: '提示', message: '操作成功', type: 'success' })
        emit('init', from[key])
        onVisable()
        if(mark == '新增' && query.o == "o_sensor" && from.class=="0"){
          let form2 = {o: "o_sensor_star", a: '新增', t: 'add', sensor_id: from[key], offline: '1'}
          api.updateApi([form2]).then((res:any) => {
            console.log('生成star成功')
          })
        }
      }
    }).catch((err) => {
      ElNotification({ title: '提示', message: '操作失败', type: 'error' })
    })
  }

  const del = (from:any, query:any, key:any, tree='') => {
    if(from.hasOwnProperty('children')&&!proxy.isNull(from.children)) return ElNotification({ title: '提示', message: '请删除子节点', type: 'error' })
    ElMessageBox.confirm('是否确定删除?', '删除提示', {confirmButtonText: '确定', cancelButtonText: '关闭', type: 'error'}).then(() => {
      let o = query.length?query[0].o : query.o
      let allFrom:any = []
      let node = '' 
      if(tree && o != "o_sensor_template"){
        proxy.childrenId(tree, from[key], key).forEach((item:any) => {
          let json = { o: o, t: 'del', a: '删除'}
          json[key] = item
          allFrom.push(json)
        })
        node = proxy.parentId(tree, from[key], key)
      }else{
        from.o = o
        from.t = "del"
        from.a = "删除"
        allFrom = [from]
      }
      api.updateApi(allFrom).then((res:any) => {
        if(res.errcode == 0){
          ElNotification({ title: '提示', message: '操作成功', type: 'success' })
          emit('init', node?node[0]:from[key])
          // 删除设备，连带删除设备统计
          if(query.o == "o_sensor" && from.class == "0"){
            let form2 = {o: "o_sensor_star", a: '删除', t: 'del', sensor_id: from.id}
            api.updateApi([form2]).then((res:any) => {
              console.log('删除star成功')
            })
          }
        }
      }).catch((err) => {
        ElNotification({ title: '提示', message: '操作失败', type: 'error' })
      })
    })
  }

  const action = (val:any, query:any, name:any) => {
    if(!val.action) return ElNotification({ title: '提示', message: '请填写动作', type: 'error' })
    let params = {sensor_id: '', code: '', action: '' }
    params.sensor_id = val.sensor_id
    params.code = val.code
    params.action = val.action
    api.remote([params]).then((res:any) => {
      if(res.errcode == 0){
        ElNotification({ title: '提示', message: '操作成功', type: 'success' })
        store.dispatch('D', varObj(name, query))
      }
    }).catch((err) => {
        ElNotification({ title: '提示', message: '操作失败', type: 'error' })
    })
  }

  const sync = (dataForm:any, query:any, name:any, key:any) => {
    ElMessageBox.confirm('是否确定同步到同类型传感器?', '重要提示！', {
      confirmButtonText: '确定',
      cancelButtonText: '关闭',
      type: 'error'
    }).then(async() => {
      let tempArr:any = []
      let data = props.state.list.filter((a:any)=>a.type == dataForm.type)
      console.log('data', data)
      data.forEach((item:any) => {
        let temp = {"o": "o_sensor", "a": '同步', t: 'upd', id: item.id }
        temp[key] = dataForm[key]
        tempArr.push(temp)
      })
      console.log('------', tempArr)
      api.updateApi(tempArr).then((res:any) => {
      if(res.errcode == 0){
          ElNotification({ title: '提示', message: '同步成功', type: 'success' })
          emit('init', dataForm[key])
        }
      }).catch((err) => {
          ElNotification({ title: '提示', message: '同步失败', type: 'error' })
      })
    })
  }

  // 同步参数
  const handleSync = (val) => {
    sync(dataForm, props.state.query, props.state.listName, val)
  }
  // 暴露给父组件
  defineExpose({
    onVisable,
    del,
    action,
  })
</script>

<style scoped lang="scss">
  :deep(input:-webkit-autofill) {
    -webkit-text-fill-color: #f5f5f5 !important;
  }
</style>
